<template>
	<view>
		<view>
			<table-title content="空调加时办理表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor" :isLast="true"></view-item>
			</view>
			<small-title :isNeed="true" content="加时日期及时间"></small-title>
			<view class="time-table">
				<uni-datetime-picker :start="startTime" @change="timeChange" :disabled="status!==-1" :hideSecond="true" v-model="datetimerange" type="datetimerange"
					 rangeSeparator="至" />
			</view>
			<view class="small-title">总时长：{{hours}} 小时</view>
			<view class="small-title">费用合计：{{spend}} 元</view>
			<view v-if="status===-1">
				<con-advance-pay-small-title content="支付方式"></con-advance-pay-small-title>
				<view style="display: flex;justify-content: center;">
					<radio-group class="payway-style" @change="changePayway">
						<label style="display: flex;">
							<radio :checked="payway[0]" :disabled="state!=='待申请'" class="first-radio" color="#FF0000" value="alipay"></radio>
							<view class="payway-choice">
								<image src="../../../static/alipay-logo.svg" class="payway-logo"></image>
								<view style="font-size: 30rpx;">支付宝支付</view>
							</view>
						</label>
						<label style="display: flex;">
							<radio :checked="payway[1]" :disabled="state!=='待申请'" class="second-radio" color="#FF0000" value="wechat"></radio>
							<view class="payway-choice">
								<image src="../../../static/wechat-logo.svg" class="payway-logo"></image>
								<view style="font-size: 30rpx;">微信支付</view>
							</view>
						</label>
					</radio-group>
				</view>
			</view>
			<small-title content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="status===1" class="mix-button">
				<view class="left-part">
					<button v-if="isConfirmable" :class="isConfirmable ? 'left-button' : 'left-button-disabled'" @click="open(0)">使用完毕</button>
					<button v-if="!isConfirmable" :class="isConfirmable ? 'left-button' : 'left-button-disabled'" @click="modOrder">使用完毕</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open(1)">取消加时</button>
				</view>
			</view>
			<view v-if="status===-1" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="onlinePay" >立即申请</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="base" :content="endType==0?'是否确认使用完毕？':'是否确认取消加时？'" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE,
		myUploadFile,
		myDownloadFile,
		syncGetOrder,
		syncPriceInfo,
	} from "../../..//util/network.js"
	import {
		processHistoryList
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				processFlag:false,
				status:-1,
				token:'',
				recordId: '待分配',                                                         //单号
				processNo:'待分配',
				state: '',																	   //状态
				status: -1,
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				hours: 0,                                                                          //加时总时长
				spend:0,                                                                           //加时总费用
				datetimerange: ['', ''],                                                           //加时区间
				startTime:'',
				payway: [true, false],                                                            //支付方式
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'受理','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'办结','time':'2020-03-03 03:33:33'}
				],                                                                                 //处理进度
				proccessListDefult:[],
				unitPrice: 0,                                                                     //加时单价，只在初次申请时通过查询对应区域价格获取值
				isConfirmable:false,
				endType:0,
			}
		},
		methods: {
			open(type) {
				this.endType = type
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				// 输入框的值
				console.log(value)
				// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
				// ...
				if(this.endType == 0){
					this.modOrder()
				}else{
					this.cancelOrder()
				}
				this.$refs.popup.close()
			},
			/*
			功能：在线支付通用方法
			参数：无
			*/
		    onlinePay(){
				if(this.hours == 0){
					uni.showModal({
						content:'请选择有效加时时段',
						showCancel:false
					});
					return 0
				}
				if(!Number(this.spend) > 0){
					uni.showModal({
						content:'该楼盘未查询到加时单价，请联系管家',
						showCancel:false
					})
					return 0
				}
		    	let orderInfo = "等后端接口"
				let orderNo = ""
		    	let paywaySingle = ''
				let _this = this
				let extraInfo = {
						startTime: this.datetimerange[0] + ":00",
						endTime: this.datetimerange[1] + ":00",
						hours: parseInt(this.hours),
						price: Number(this.spend),
						commentMsg: '发起申请',                       //操作信息
					}
		    	if(this.payway[0]){
		    		paywaySingle = 'alipay'
		    	}else{
		    		paywaySingle = 'wxpay'
		    	}
		    	uni.request({
		    		url:`${ONLINE_SERVER_ADDRESS_BASE}/pay/pay`,
		    		header: {
		    			'Authorization': this.token,
		    		},
		    		data: {
		    			orderName: "空调加时",
		    			payPlatform: paywaySingle,                        //待写入工单内容
						orderType:0,
						extraInfo:JSON.stringify(extraInfo),
						amount: Number(this.spend),
						recordId:-1,
		    		},
		    		method:'POST',
		    		success: function (res) {
		    			console.log("提交成功",res.data);
		    			if(res.data.code == 200){
		    				if(paywaySingle == 'wxpay'){
		    					orderInfo = res.data.data.wxPayOrderInfo
								orderNo = res.data.data.orderNo
		    				}else{
		    					orderInfo = res.data.data.aliPayOrderInfo
								orderNo = res.data.data.orderNo
		    				}
		    				uni.requestPayment({  
		    					provider: paywaySingle,  
		    					orderInfo: orderInfo,  
		    					success: (e) => {  
		    						console.log(e);  
									uni.navigateBack()
									// _this.addOrder(orderNo)
		    					},  
		    					fail: (e) => {  
		    						uni.showModal({  
		    							content: "支付失败,原因为: " + e.errMsg,  
		    							showCancel: false  
		    						})  
		    					}  
		    				});
		    			}
		    		}
		    	})
		    },
			
			/*
			功能：选择支付方式
			参数：无
			*/
			changePayway(e){
				console.log('-change事件:', e.detail.value)
				if(e.detail.value == "alipay"){
					this.payway=[true,false];
				}else{
					this.payway=[false,true];
				}
			},
			
			/*
			功能：计算加时费用
			参数：无
			*/
			timeChange(e){
				// console.log('-change事件:', e)
				let timeSum = Date.parse(e[1].replace(/-/g, '/')) - Date.parse(e[0].replace(/-/g, '/'))
				//计算出相差天数  
				var days=Math.floor(timeSum/(24*3600*1000))  
				//计算出小时数  
				var leave1=timeSum%(24*3600*1000)    //计算天数后剩余的毫秒数  
				var hours=Math.floor(leave1/(3600*1000))  
				//计算相差分钟数  
				var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数  
				var minutes=Math.floor(leave2/(60*1000))  
				if(minutes > 0){
					hours = hours + 1 + days * 24
				}else{
					hours = hours + days * 24
				}
				if(hours < 0){
					uni.showModal({
						content:'请选择正确的加时区间',
						showCancel:false
					})
					this.hours = 0
					this.spend = 0
					return 0
				}
				if(hours < 2){
					uni.showModal({
						content:'加时时间不能小于两小时',
						showCancel:false
					})
					this.hours = 0
					this.spend = 0
					return 0
				}
				this.hours = hours
				this.spend = hours * this.unitPrice
			},
			
			/*
			功能：工单详细页处理通用函数
			参数：
			option：操作类型（先定成 创建、写入、查询）
			*/
			addOrder(orderNo){
				console.log("[info]","工单已创建，工单号为：待分配")
				console.log("[info]",this.datetimerange[0])
				console.log("[info]",this.datetimerange[1])
				console.log("[info]",parseInt(this.hours))
				console.log("[info]",Number(this.spend))
				if(!parseInt(this.hours) > 0){
					uni.showModal({
						content:'请选择正确的加时区间',
						showCancel:false
					})
					return 0
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/overtime-ac/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						orderNo:orderNo,
						startTime: this.datetimerange[0] + ":00",
						endTime: this.datetimerange[1] + ":00",
						hours: parseInt(this.hours),
						price: Number(this.spend),
						commentMsg: '发起申请',                       //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("空调加时add", res)
						if(res.data.code == 200){
							uni.navigateBack()
						}
					}
				})
			},
			modOrder(){
				if(!this.isConfirmable){
					uni.showModal({
						content:'当前空调加时计划暂未执行完毕',
						showCancel:false
					})
					return -1
				}
				console.log("[info]","收到空调加时办结：" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/overtime-ac/finish/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: '使用完毕，办结'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("空调加时申请办结调用失败")
					}
				})
			},
			cancelOrder(){
				console.log("[info]","收到空调加时办结：" + this.recordId)
				var date = new Date();
				var orderStartDate = new Date(this.datetimerange[0]);
				var hours = date.getHours();
				// if((orderStartDate.getDay() == date.getDay()) && (orderStartDate.getMonth() == date.getMonth())){
					if(hours > 18){
						uni.showModal({
							content:'请在每天18：00之前，且提前一小时取消空调加时',
							showCancel:false
						})
						return -1
					}
				// }
				if((Date.parse(orderStartDate.replace(/-/g, '/')) - Date.now()) < 6000000){
					uni.showModal({
						content:'请在每天18：00之前，且提前一小时取消空调加时',
						showCancel:false
					})
					return -1
				}
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/overtime-ac/cancel/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: '申请取消加时'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("用户申请取消调用失败")
					}
				})
			},
			getOrder(){
				let a = syncGetOrder("overtime-ac/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 this.processFlag = false
						 this.status = parseInt(res.data.data.status)
						 switch(parseInt(this.status)) {
						 	 case 0:
						 		this.state = "待指派工程"
						 		break;
						 	 case 1:
						 		this.state = "计划执行中"
						 		break;
						 	 case 2:
						 		this.state = "加时完毕"
						 		break;
						 	 case 3:
						 		this.state = "取消待审核"
						 		break;
						 	 case 4:
						 		this.state = "待工程关闭"
						 		break;
						 	 case 5:
						 		this.state = "待财务退款"
						 		break;
						 	 case 6:
						 		this.state = "加时已取消"
						 		break;
						 	 case 7:
						 		this.state = "待工程确认"
						 		break;
						      default:
						         this.state = "待申请"
						 } 
						 this.$set(this.datetimerange, 0, res.data.data.startTime)
						 this.$set(this.datetimerange, 1, res.data.data.endTime)
						 this.hours = res.data.data.hours
						 this.spend = res.data.data.price
						 this.processNo = res.data.data.processNo
						 this.proccessListDefult = processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
						 this.isConfirmable = false
						 let curDate = Date.parse(new Date())
						 let timeSum = curDate - Date.parse(this.datetimerange[0].replace(/-/g, '/'))
						 if(timeSum > 1000){
						 	this.isConfirmable = true
						 }
						 this.$forceUpdate()
					}
				})
			},
			back(){
				uni.navigateBack()
			}
		},
		onLoad(option) {
			//传入单号
			let userInfo = uni.getStorageSync('userinfo')
			if(userInfo != null){
				this.userMsg.userBuilding = userInfo.title
				this.userMsg.userFloor = userInfo.floor
				this.recordId = option.id
				this.state = option.state
				this.token = uni.getStorageSync('token')
			}else{
				uni.navigateTo('../../login/login')
			}
		},
		mounted() {
			if(this.state != '待申请'){
				this.getOrder()
			}else{
				//如果是新建表单则不查询
				let buildId = uni.getStorageSync('userinfo').buildId
				let price = syncPriceInfo(4,1,buildId) //查询单价 空调加时类，全区域类
				price.then((res) => {
					console.log(res.data)
					if(res.data.data.length == 0){
						uni.showModal({
							content:'该楼盘未查询到加时单价，请联系管家',
							showCancel:false
						})
						// uni.navigateBack()
						return 0
					}
					this.unitPrice = res.data.data[0].price
					this.hours = 2
					this.spend = this.hours * this.unitPrice
				})
				let  date=new Date();
				let  date2hours = new Date(Date.now() + (3600 * 1000 * 2))
				let  newdate=date.toLocaleString('chinese', { hour12: false }).replace("/", "-").replace("/", "-");
				let newdate2hours = date2hours.toLocaleString('chinese', { hour12: false }).replace("/", "-").replace("/", "-");
				this.startTime = newdate
				this.$set(this.datetimerange, 0, newdate)
				this.$set(this.datetimerange, 1, newdate2hours)
			}
		}
	}
</script>

<style>
	page{
		background-color: #F1F1F1
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.left-button-disabled{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #a6a6a6;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.payway-style {
		display: flex;
		flex-direction: column;
		width: 80%;
		margin-left: 18rpx;
	}
	.first-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-bottom: none;
		border-right: none;
	}
	.second-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-right: none;
		width: 50rpx;
	}
	.payway-choice {
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		border: solid 0rpx #C8C7CC;
		width: 600rpx;
		border-left: none;
	}
	.payway-logo {
		width: 50rpx;
		height: 50rpx;
		margin: 0 25rpx 0 25rpx;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
	}
	.time-table{
		margin: 20rpx 20rpx 20rpx 50rpx;
		width: 87.5%;
	}
</style>
